<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryOptions"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          value-key="id"
          placeholder="选择产品分类"
          clearable
        />
      </el-form-item>
      <el-form-item label="产品材质" prop="material">
        <el-input
          v-model="queryParams.material"
          placeholder="请输入产品材质"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品等级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择产品等级" clearable>
          <el-option label="优等品" value="优等品" />
          <el-option label="一等品" value="一等品" />
          <el-option label="二等品" value="二等品" />
          <el-option label="三等品" value="三等品" />
          <el-option label="合格品" value="合格品" />
          <el-option label="次品" value="次品" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qep:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qep:product:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['qep:product:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="code" />
      <el-table-column label="产品名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="产品分类" align="center" prop="categoryName" :show-overflow-tooltip="true" />
      <el-table-column label="产品规格" align="center" prop="specification" :show-overflow-tooltip="true" />
      <el-table-column label="产品材质" align="center" prop="material" />
      <el-table-column label="计量单位" align="center" prop="unit" />
      <el-table-column label="产品等级" align="center" prop="grade" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qep:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qep:product:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['qep:product:query']">详情</el-button>
          <el-dropdown>
            <el-button link type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleProcess(scope.row)" icon="Connection">工序配置</el-dropdown-item>
                <el-dropdown-item @click="handleStandard(scope.row)" icon="Document">质量标准</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="basic">
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品编码" prop="code">
                  <el-input v-model="form.code" placeholder="请输入产品编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入产品名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品分类" prop="categoryId">
                  <el-tree-select
                    v-model="form.categoryId"
                    :data="categoryOptions"
                    :props="{ label: 'name', value: 'id', children: 'children' }"
                    value-key="id"
                    placeholder="选择产品分类"
                    check-strictly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计量单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入计量单位" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="技术参数" name="tech">
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品规格" prop="specification">
                  <el-input v-model="form.specification" placeholder="请输入产品规格" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品材质" prop="material">
                  <el-input v-model="form.material" placeholder="请输入产品材质" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品等级" prop="grade">
                  <el-select v-model="form.grade" placeholder="请选择产品等级">
                    <el-option label="优等品" value="优等品" />
                    <el-option label="一等品" value="一等品" />
                    <el-option label="二等品" value="二等品" />
                    <el-option label="三等品" value="三等品" />
                    <el-option label="合格品" value="合格品" />
                    <el-option label="次品" value="次品" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 可以根据需要添加更多技术参数 -->
          </el-tab-pane>
          <el-tab-pane label="关联文档" name="docs">
            <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="handleFileChange"
              multiple
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button class="ml-3" type="success" @click="submitUpload">
                上传到服务器
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  请上传产品图纸、技术标准等相关文档，支持jpg/png/doc/pdf文件
                </div>
              </template>
            </el-upload>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
          <div class="el-upload__tip" style="color:red">提示：仅允许导入xls、xlsx格式文件！</div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/qep/product";
import { listCategoryTree } from "@/api/qep/category";
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { ArrowDown, UploadFilled } from '@element-plus/icons-vue';

const router = useRouter();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 产品表格数据
const productList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 默认选中的标签页
const activeName = ref('basic');
// 产品分类树选项
const categoryOptions = ref([]);
// 文件列表
const fileList = ref([]);
// 状态数据字典
const statusOptions = ref([
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  categoryId: undefined,
  material: undefined,
  grade: undefined,
  status: undefined
});

// 表单参数
const form = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  categoryId: undefined,
  specification: undefined,
  material: undefined,
  unit: undefined,
  grade: '优等品', // 默认为优等品
  status: 1,
  remark: undefined
});

// 表单校验
const rules = ref({
  code: [
    { required: true, message: "产品编码不能为空", trigger: "blur" }
  ],
  name: [
    { required: true, message: "产品名称不能为空", trigger: "blur" }
  ],
  categoryId: [
    { required: true, message: "产品分类不能为空", trigger: "blur" }
  ],
  unit: [
    { required: true, message: "计量单位不能为空", trigger: "blur" }
  ]
});

// 文件上传参数
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + sessionStorage.getItem("token") },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/qep/product/importData"
});

// 表单引用
const productRef = ref();
const uploadRef = ref();

/* 查询产品列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/* 查询产品分类下拉树结构 */
function getTreeselect() {
  listCategoryTree().then(response => {
    categoryOptions.value = response.data;
  });
}

/* 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/* 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    categoryId: undefined,
    specification: undefined,
    material: undefined,
    unit: undefined,
    grade: '优等品',
    status: 1,
    remark: undefined
  };
  fileList.value = [];
  activeName.value = 'basic';
  productRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    code: undefined,
    name: undefined,
    categoryId: undefined,
    material: undefined,
    grade: undefined,
    status: undefined
  };
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTreeselect();
  open.value = true;
  title.value = "添加产品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTreeselect();
  const id = row.id || ids.value[0];
  getProduct(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产品";
  });
}

/** 提交按钮 */
function submitForm() {
  productRef.value.validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateProduct(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProduct(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const productIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除选中的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delProduct(productIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有产品数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    ElMessage.success("导出成功");
    // TODO: 实现导出功能
    // window.location.href = "/qep/product/export";
  }).catch(() => {});
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "产品导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  // TODO: 实现下载模板功能
  // window.location.href = "/qep/product/importTemplate";
}

/** 文件上传中处理 */
function handleFileUploadProgress() {
  upload.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response) {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
  ElMessage.success("导入成功");
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

/** 选择文件 */
function handleFileChange(file, fileList) {
  fileList.value = fileList;
}

/** 上传文件 */
function submitUpload() {
  // TODO: 实现文件上传到服务器功能
  console.log("文件上传", fileList.value);
  ElMessage.success("文件上传成功");
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 查看详情 */
function handleDetail(row) {
  router.push({ 
    path: '/product/detail', 
    query: { id: row.id } 
  });
}

/** 工序配置 */
function handleProcess(row) {
  router.push({ 
    path: '/product/process', 
    query: { id: row.id } 
  });
}

/** 质量标准 */
function handleStandard(row) {
  router.push({ 
    path: '/product/standard', 
    query: { id: row.id } 
  });
}

onMounted(() => {
  getList();
  getTreeselect();
});
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style> 